package serverlet;

import Server.ManagerServer;
import test.SqlInit;
import user.Manager;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet", urlPatterns = "/login1")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String account = request.getParameter("account");
        System.out.println("获取到的用户名为："+account);
        String password = request.getParameter("password");
        System.out.println("获取到的密码是："+password);
        //创建ManagerServerice
        ManagerServer managerServer = new ManagerServer();
        Manager manager = managerServer.managerLoginServer(new Manager(account, password));
        if(null == manager){
            System.out.println("登陆失败，账号或密码失败");
            request.setAttribute("error","登陆失败，用户名或密码错误");
            //实现服务器跳转

            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request,response);
        }else {
            System.out.println("登陆成功，欢迎使用");
            Cookie[] cookies = request.getCookies();
                for(Cookie tc : cookies){
                    if("account".equals(tc.getName())){
                        tc.setValue(account);
                        System.out.println(tc.getValue());
                        tc.setMaxAge(60*60*24*7);
                        request.getSession().setAttribute("account",manager.getAccount());
                        response.addCookie(tc);
                    }else if("password".equals(tc.getName())){
                        tc.setValue(password);
                        System.out.println(tc.getValue());
                        tc.setMaxAge(60*60*24*7);
                        request.getSession().setAttribute("password",manager.getPassword());
                        response.addCookie(tc);
                    }
                }
            }
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/managerinit");
            requestDispatcher.forward(request,response);
        }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
